//
//  UITextView+Extension.swift
//  weibo002
//
//  Created by 黑眼圈 on 16/5/2.
//  Copyright © 2016年 heiyan. All rights reserved.
//

import Foundation



extension UITextView {
    
    
    
    
    //将表情图片转化成字符串发送到新浪微博
    var emotionText: String? {

            
            //定义一个可变的字符串
            var result = ""
            
            //记录文本框的富文本
            let attributed = self.attributedText
            
            //遍历富文本中的内容
            attributed.enumerateAttributesInRange(NSMakeRange(0, attributed.length), options: []) { (dict, range, _) -> Void in
                
                //如果里面有附件
                if let attr = dict["NSAttachment"] as? HZTextAttachment {
 
                    //是图片表情就取到描述字符串
                    result += attr.model?.chs ?? ""
                }else {
                    
                    //不是表情就返回文字,需要把文件截取出来再添加上去
                    result += ((attributed.string) as NSString).substringWithRange(range)
                }
                
            }
 
            return result
   
    }
    
    
    
    //填写富文本到文本框里
    func insertImgText(model:HZEmotionModel){
        
        
        
        let muAttributed = NSMutableAttributedString(attributedString: self.attributedText)
        
        //获取图片
        let img = UIImage(named: "\(model.pathString ?? "")/\(model.png ?? "")", inBundle: HZEmotionVM.sharedEmotion.getBundle(), compatibleWithTraitCollection: nil)
        
        //定义一个装载图片的附件
        let attatchment = HZTextAttachment()
        
        //赋值模型
        attatchment.model = model
        
        //赋值图片
        attatchment.image = img
        
        //设置附件的大小,并让附件往下偏一点好于 emoji 表情对齐
        attatchment.bounds = CGRect(x: 0, y: -4, width: self.font!.lineHeight, height: self.font!.lineHeight)
        
        //通过附件生成不可变富文本
        let arributed = NSAttributedString(attachment: attatchment)
        
        //获取光标所在的位置
        var range = self.selectedRange
        
        //把含有图片附件的不可变富文本添加到可变富文本中
        muAttributed.replaceCharactersInRange(range, withAttributedString: arributed)
        
        //设置字体的大小
        muAttributed.addAttribute(NSFontAttributeName, value: self.font!, range: NSMakeRange(0, muAttributed.length))
        
        //把拼接好的富文本给文本框
        self.attributedText = muAttributed
        
        
        //最后让光标回到输入后的位置
        range.location += 1
        range.length = 0
        self.selectedRange = range
        
        
        //设置按钮,占位文本和图片表情之前的联动
        
        //有表情图片让占位文字隐藏
        NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
        
        //手动调用有表情图片就让发送按钮出现的代理方法
        self.delegate?.textViewDidChange!(self)

        
        
        
    }
    
    
}